﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using System.Threading;

namespace RemotePC.NET
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            isConnecting = false;
            CheckCount = 0;

            // 这句可解决非创建控件线程访问控件引起的异常，但可能会引发其它的线程异常。
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            ComputerRemote.StatusChanged += new ComputerRemote.StatusChangedHandler(SetStatustoTips);
        }

        private ComputerRemote [] crs;
        private bool isConnecting;
        private int CheckCount;
        private SettingXML sx;
        private bool isAllDone;

        private void MainForm_Load(object sender, EventArgs e)
        {
            sx = new SettingXML("", "setting.xml");
            try
            {
                sx.InitXML();
            }
            catch (System.IO.FileNotFoundException fnfex)
            {
                MessageBox.Show("配置文件 setting.xml 未找到。将使用默认配置。", "配置文件未找到", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                sx.BacktoDefault();
                sx.InitXML();
            }
            catch (System.Exception ex)
            {
                if (DialogResult.OK == MessageBox.Show("读取配置文件出现异常。点击确定后将使用默认配置。\n异常详细信息：" + ex.Message, "配置文件异常", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
                {
                    sx.BacktoDefault();
                    sx.InitXML();
                }
                else
                {
                    this.Close();
                }                
            }
            finally
            {
            }
            crs = new ComputerRemote[]
            {
                new ComputerRemote("PC-01", sx.ReadSetting("PC-01", "path"), sx.ReadSetting("PC-01", "username"), sx.ReadSetting("PC-01", "password"), PC01_cb),
                new ComputerRemote("PC-02", sx.ReadSetting("PC-02", "path"), sx.ReadSetting("PC-02", "username"), sx.ReadSetting("PC-02", "password"), PC02_cb), 
                new ComputerRemote("PC-03", sx.ReadSetting("PC-03", "path"), sx.ReadSetting("PC-03", "username"), sx.ReadSetting("PC-03", "password"), PC03_cb), 
                new ComputerRemote("PC-04", sx.ReadSetting("PC-04", "path"), sx.ReadSetting("PC-04", "username"), sx.ReadSetting("PC-04", "password"), PC04_cb), 
                new ComputerRemote("PC-05", sx.ReadSetting("PC-05", "path"), sx.ReadSetting("PC-05", "username"), sx.ReadSetting("PC-05", "password"), PC05_cb), 
                new ComputerRemote("PC-06", sx.ReadSetting("PC-06", "path"), sx.ReadSetting("PC-06", "username"), sx.ReadSetting("PC-06", "password"), PC06_cb), 
                new ComputerRemote("PC-07", sx.ReadSetting("PC-07", "path"), sx.ReadSetting("PC-07", "username"), sx.ReadSetting("PC-07", "password"), PC07_cb), 
                new ComputerRemote("PC-08", sx.ReadSetting("PC-08", "path"), sx.ReadSetting("PC-08", "username"), sx.ReadSetting("PC-08", "password"), PC08_cb), 
                new ComputerRemote("PC-09", sx.ReadSetting("PC-09", "path"), sx.ReadSetting("PC-09", "username"), sx.ReadSetting("PC-09", "password"), PC09_cb), 
                new ComputerRemote("PC-10", sx.ReadSetting("PC-10", "path"), sx.ReadSetting("PC-10", "username"), sx.ReadSetting("PC-10", "password"), PC10_cb), 
                new ComputerRemote("PC-11", sx.ReadSetting("PC-11", "path"), sx.ReadSetting("PC-11", "username"), sx.ReadSetting("PC-11", "password"), PC11_cb), 
            }; //Check

            foreach (ComputerRemote cr in crs)
            {                
                //PCtoolTip.SetToolTip(cr.MyBox, "\n计算机名：" + cr.Name + "\nIP：" + cr.Path + "\n状态：" + cr.GetStatus());
                cr.MyBox.ImageIndex = 2;                
                cr.MyBox.CheckedChanged += new System.EventHandler(this.CheckedChanged);
            }            
        }

        private void remoteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ComputerRemote cr = new ComputerRemote("EVA", "192.168.88.224", "Eva", "123");
            if (cr.InitConnect())
                cr.DoCommand("");
            else
                MessageBox.Show(cr.Status.ToString());
        }

        private void AllGroupEnable(bool value)
        {
            allCheck_btn.Enabled = value;
            allUnCheck_btn.Enabled = value;
            Reboot_btn.Enabled = value;
            Shutdown_btn.Enabled = value;
            PC01_cb.AutoCheck = value;
            PC02_cb.AutoCheck = value;
            PC03_cb.AutoCheck = value;
            PC04_cb.AutoCheck = value;
            PC05_cb.AutoCheck = value;
            PC06_cb.AutoCheck = value;
            PC07_cb.AutoCheck = value;
            PC08_cb.AutoCheck = value;
            PC09_cb.AutoCheck = value;
            PC10_cb.AutoCheck = value;
            PC11_cb.AutoCheck = value;

            //groupBox1.Enabled = value;
            //groupBox2.Enabled = value;
            //groupBox3.Enabled = value;
        }

        private void Check_btn_Click(object sender, EventArgs e)
        {
            
            if (isConnecting)
            {
                bgWorker1.CancelAsync();
                toolStripStatusTxt.Text = "等待当前操作结束…   ";
            }
            else
            {
                AllGroupEnable(false);
                Check_btn.Text = "取消当前操作";
                toolStripProgressBar1.Enabled = true;
                toolStripProgressBar1.Maximum = CheckCount;
                toolStripStatusGif.Enabled = true;
                bgWorker1.RunWorkerAsync();
                toolStripStatusTxt.Text = "检查选定计算机状态…   ";
            }
        }

        private void allCheck_btn_Click(object sender, EventArgs e)
        {
            foreach (ComputerRemote cr in crs)
            {
                cr.MyBox.Checked = true;
            }
        }

        private void allUnCheck_btn_Click(object sender, EventArgs e)
        {
            foreach (ComputerRemote cr in crs)
            {
                cr.MyBox.Checked = false;
            }
        }

        private void CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.Checked)
            {
                CheckCount++;
                if (cb.ImageIndex <= 7)
                {
                    cb.ImageIndex += 8;
                }
            }
            else
            {
                CheckCount--;
                if (cb.ImageIndex >= 8)
                {
                    cb.ImageIndex -= 8;
                }
            }
        }

        private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            isConnecting = true;
            int n = 0;
            foreach (ComputerRemote cr in crs)
            {
                if (bgWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                
                if (cr.MyBox.Checked)
                {
                    bgWorker1.ReportProgress(n++);
                    cr.MyBox.UseWaitCursor = true;
                    toolStripStatusOtherTxt.Text = "正在检查 " + cr.Name + "…";
                    if (cr.InitConnect())
                    {
                        cr.MyBox.ImageIndex = 12;
                    }
                    else
                    {
                        switch (cr.Status)
                        {
                        case -8:
                            cr.MyBox.ImageIndex = 15;
                        	break;
                        case -9:
                            cr.MyBox.ImageIndex = 8;
                        	break;
                        case -10:
                            cr.MyBox.ImageIndex = 11;
                            break;
                        case -11:
                            cr.MyBox.ImageIndex = 10;
                            break;
                        case -2:
                        case -3:
                        case -4:
                        case -5:
                            cr.MyBox.ImageIndex = 1;
                        	break;
                        case -6:
                            cr.MyBox.ImageIndex = 15;
                            break;
                        case -7:
                            cr.MyBox.ImageIndex = 13;
                            break;
                        case -1:
                            cr.MyBox.ImageIndex = 14;
                        	break;
                        default :
                            cr.MyBox.ImageIndex = 9;
                        	break;
                        }
                    }
                    cr.MyBox.UseWaitCursor = false;
                }                
            }
        }

        private void bgWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isConnecting = false;
            //AllGroupEnable(true);
            Check_btn.Text = "检查选定计算机状态";
            if (e.Cancelled)
            {
                toolStripProgressBar1.Value = 0;
                toolStripStatusOtherTxt.Text = "剩余检查已被用户取消。";
            }
            else
            {
                toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
                toolStripStatusOtherTxt.Text = "已完成所有检查。";
            }
            toolStripProgressBar1.Enabled = false;
            toolStripStatusGif.Enabled = false;
            toolStripStatusTxt.Text = "等待命令   ";
            AllGroupEnable(true);
        }

        private void bgWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }

        private void Setting_btn_Click(object sender, EventArgs e)
        {
            (new SettingForm()).ShowDialog();
        }

        private void PCtoolTip_Popup(object sender, PopupEventArgs e)
        {         
        }

        private void SetStatustoTips(object sender)
        {
            ComputerRemote cr = (ComputerRemote)sender;
            //Invoke(new EventHandle(ResetTips), cr); 
            PCtoolTip.SetToolTip(cr.MyBox, "计算机名：" + cr.Name + "\nIP：" + cr.Path + "\n用户名：" + cr.Username + "\n状态：" + cr.GetStatus());
        }

        //private void ResetTips(ComputerRemote cr)
        //{
        //    PCtoolTip.SetToolTip(cr.MyBox, "\n计算机名：" + cr.Name + "\nIP：" + cr.Path + "\n状态：" + cr.GetStatus());
        //}

        private void Reboot_btn_Click(object sender, EventArgs e)
        {
            isAllDone = true;
            String str = "";
            foreach (ComputerRemote cr in crs)
            {
                if (cr.MyBox.Checked && !(cr.DoCommand("Reboot")))
                {
                    if (isAllDone)
                    {
                        isAllDone = false;
                    }
                    str += cr.Name + "、";
                }
            }
            if (!isAllDone)
            {
                MessageBox.Show("对 " + str.Substring(0, str.Length - 1) + " 的重启操作失败！\n请先检查目标计算机状态，并确保其为连接正常。", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Shutdown_btn_Click(object sender, EventArgs e)
        {
            isAllDone = true;
            String str = "";
            foreach (ComputerRemote cr in crs)
            {
                if (cr.MyBox.Checked && !(cr.DoCommand("Shutdown")))
                {
                    if (isAllDone)
                    {
                        isAllDone = false;
                    }
                    str += cr.Name + "、";                
                }
            }
            if (!isAllDone)
            {
                MessageBox.Show("对 " + str.Substring(0, str.Length - 1) + " 的关机操作失败！\n请先检查目标计算机状态，并确保其为连接正常。", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Setting_btn_Click(sender, e);
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new AboutBox1()).ShowDialog();
        }
    }
}
